﻿using YY.Admin.Core;
using System.Reflection;
using YY.Admin.Services.Service.Auth;

namespace YY.Admin
{
    public static class ServiceExtensions
    {
        /// <summary>
        /// 注册服务
        /// </summary>
        public static void AddService(this IContainerRegistry containerRegistry)
        {
            //// 注册日志服务为单例
            containerRegistry.RegisterSingleton<ILoggerService, SerilogLoggerService>();
            // 自动扫描并注册应用层服务
            RegisterServicesByAssembly(containerRegistry, typeof(ISysAuthService).Assembly);
        }
        /// <summary>
        /// 自动注册程序集中所有服务
        /// </summary>
        private static void RegisterServicesByAssembly(IContainerRegistry containerRegistry, Assembly assembly)
        {
            // 获取所有公开的非抽象类
            var serviceTypes = assembly.GetExportedTypes()
                .Where(t => t.IsClass && !t.IsAbstract);

            foreach (var implementationType in serviceTypes)
            {
                // 查找服务接口（名称以"I"开头，去掉首字母后匹配）
                var serviceInterface = implementationType.GetInterfaces()
                    .FirstOrDefault(i => i.Name == $"I{implementationType.Name}");

                // 如果没有直接匹配的接口，尝试查找其他接口
                if (serviceInterface == null)
                {
                    // 备选方案1：注册所有实现的接口（适合多接口实现）
                    RegisterAllInterfaces(containerRegistry, implementationType);

                    // 备选方案2：只注册主接口
                    // serviceInterface = implementationType.GetInterface($"I{implementationType.Name}");
                }
                else
                {
                    // 注册找到的接口
                    RegisterService(containerRegistry, serviceInterface, implementationType);
                }
            }
        }

        /// <summary>
        /// 注册服务到容器
        /// </summary>
        private static void RegisterService(
            IContainerRegistry containerRegistry,
            Type serviceType,
            Type implementationType)
        {
            // 根据命名约定判断生命周期
            bool isSingleton = implementationType.Name.EndsWith("Service") ||
                               implementationType.Name.EndsWith("Repository");

            // 根据基类判断生命周期
            bool isSingletonByBase = typeof(ISingletonDependency).IsAssignableFrom(implementationType);

            // 根据特性判断生命周期
            var attribute = implementationType.GetCustomAttribute<LifecycleAttribute>();
            var lifecycle = attribute?.Lifecycle ?? Lifecycle.Transient;

            // 确定注册方式
            if (isSingleton || isSingletonByBase || lifecycle == Lifecycle.Singleton)
            {
                containerRegistry.RegisterSingleton(serviceType, implementationType);
                Console.WriteLine($"注册单例服务: {serviceType.Name} -> {implementationType.Name}");
            }
            else
            {
                containerRegistry.Register(serviceType, implementationType);
                Console.WriteLine($"注册瞬时服务: {serviceType.Name} -> {implementationType.Name}");
            }
        }

        /// <summary>
        /// 注册所有实现的接口
        /// </summary>
        private static void RegisterAllInterfaces(IContainerRegistry containerRegistry, Type implementationType)
        {
            var interfaces = implementationType.GetInterfaces()
                .Where(i => i != typeof(IDisposable) &&
                             !i.Name.StartsWith("_") && // 排除某些特殊接口
                             i.Assembly == implementationType.Assembly); // 只注册同程序集接口

            foreach (var serviceType in interfaces)
            {
                RegisterService(containerRegistry, serviceType, implementationType);
            }

            if (!interfaces.Any())
            {
                // 如果没有接口，直接注册具体类型
                containerRegistry.Register(implementationType);
                Console.WriteLine($"注册具体类型: {implementationType.Name}");
            }
        }
}
}
